package cn.datastruct.four;
//定义节点
//int,next
class LinkedStackNode<T>{
    public T num;
    public LinkedStackNode next;

    public LinkedStackNode(T num) {
        this.num = num;
    }

    public LinkedStackNode() {
    }

    @Override
    public String toString() {
        return "LinkedStackNode{" +
                "num=" + num +
                '}';
    }
}
/*  用链表实现栈，头插法：
        1，定义栈顶
        2，isEmpty(),判断是否栈空
        3，push(int a),添加元素
        4，pop(),出栈
        5,求栈长度
        6,求栈最大容量
        7,打印栈

* */

public class LinkedStack<T> extends Stack{
    public LinkedStackNode lsn;

    //构造栈，1，定义栈顶
    public LinkedStack() {
        this.lsn = null;
    }

    @Override
    //2，isEmpty(),判断是否栈空
    public boolean isEmpty(){return this.lsn == null;}

    @Override
    //3，isFull(),判断是否栈满
    public boolean isFull(){return this.lsn == null;}

    @Override
    public void push() {

    }

    //4，push(int a),添加元素
    public void push(LinkedStackNode ln){
        ln.next = this.lsn;
        this.lsn = ln;
    }

    @Override
    //5，pop(),出栈
    public void pop(){
        if (length() == 0){
            throw new RuntimeException("链表长度为空");
        }
        this.lsn = this.lsn.next;
    }

    @Override
    //6,求栈长度
    public int length(){
        LinkedStackNode temp = this.lsn;
        int length = 0;
        while (temp != null){
            temp = temp.next;
            length++;
        }
        return length;
    }

    @Override
    //7,打印栈
    public void showStack(){
        LinkedStackNode temp = this.lsn;
        while (temp != null){
            System.out.println(temp);
            temp = temp.next;
        }
    }
}
